<template>
<n-upload
    multiple
    directory-dnd
    :action="BASE+'/upload'"
    name="avatar"
    @finish="handelfinish"
    @remove="handelremove"
    :max="1"
  >
    <n-upload-dragger>
        <img v-if="preview" :src="BASE+preview" alt="" style="height: 100px;">
        <div v-else>
            <div style="margin-bottom: 12px">
                <n-icon size="48" :depth="3">
                <AddOutline />
                </n-icon>
            </div>
            <n-text style="font-size: 16px">
                点击或者拖动文件到该区域来上传
            </n-text>
        </div>
    </n-upload-dragger>
  </n-upload>
</template>

<script setup>

import { AddOutline } from '@vicons/ionicons5';
import { useMessage } from 'naive-ui';
import { BASE } from '../config';
const message = useMessage();
const props = defineProps(['modelValue'])// 此处作用等同于this.$props.modelValue
const emit = defineEmits(['update:modelValue']) // 此处作用等同于this.$emit('update:modelValue')
const preview = ref('')
const handelfinish = (options)=>{
    console.log("上传成功",options.event.target.response);
    let res = JSON.parse(options.event.target.response)
    console.log(res);
    let {code,msg,path} = res
    let msgState = ['error','success']
    message[msgState[code]](msg)//弹出提示框
    preview.value = path //预览图片
    emit('update:modelValue',path)//将图片路径传给当前组件的调用者v-model
}
const handelremove = ()=>{
    preview.value = '' //清空预览图片
    emit('update:modelValue','')//清空将图片路径传给当前组件的调用者v-model
}
preview.value = props.modelValue// 接收外部传递的图片路径
</script>

<style lang="scss" scoped>

</style>